package edu.umd.mhealth.lab6;


import android.os.AsyncTask;

import org.achartengine.GraphicalView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

import edu.umd.mhealth.views.WeightHistoryView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class HttpGetHistoryTask extends AsyncTask<String, Void, double[]> {
	private ViewGroup mContainer; 
	private OAuthService service;
	private Token accessToken;

	public HttpGetHistoryTask(ViewGroup container, OAuthService service, Token accessToken){
		this.mContainer = container;
		this.service = service;
		this.accessToken = accessToken;
	}

	@Override
	protected double[] doInBackground(String... params) {
		OAuthRequest oauth_request = new OAuthRequest(Verb.GET, params[0]); 
		service.signRequest(accessToken, oauth_request); 
		Response response = oauth_request.send(); 

		double[] result = null;
		if (response.getCode() == 200){
			JSONObject json;

			try {
				json = new JSONObject(response.getBody());
				JSONArray arr = json.getJSONArray("body-weight"); 
				result = new double[7];				
				for (int i = 0; i < 7; i++){
					JSONObject reading = arr.getJSONObject(i);
					result[i] = reading.getDouble("value");
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		return result;
	}

	protected void onPostExecute(double[] response){
		if (response == null){
			Toast.makeText(mContainer.getContext(), "server error", 30).show();
		} else {
			GraphicalView toAdd = new WeightHistoryView(mContainer.getContext(), response).getGraph();
			LinearLayout layout = (LinearLayout) mContainer.findViewById(R.id.display);
			View toRemove = (View) layout.getChildAt(0);
			layout.removeView(toRemove);
			layout.addView(toAdd, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		}
	}
}

